package models

import (
	"time"

	"github.com/astaxie/beego/orm"
)

type ChatError struct {
	Id         int       `orm:"column(id);auto"`
	Issuccess  int       `orm:"column(issuccess);"`
	Syncnum    int       `orm:"column(syncnum);"`
	Msg        string    `orm:"column(msg);size(255);null"`
	Code       int       `orm:"column(code);size(10);null"`
	Starttime  string    `orm:"column(starttime);size(30);null"`
	Createtime time.Time `orm:"column(createtime);type(timestamp);null;auto_now"`
}

func (t *ChatError) TableName() string {
	return "chat_error"
}

func init() {
	orm.RegisterModel(new(ChatError))
}

func ChatErrorAdd(m *ChatError) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(m)
	return
}

func ChatErrorRead() (m *ChatError, err error) {
	o := orm.NewOrm()
	m = &ChatError{}
	err = o.QueryTable(new(ChatError)).Filter("Issuccess", 0).Filter("Syncnum__lte", 5).Limit(1).One(m)
	return
}

func ChatErrorUpdate(id int, issucc int) (err error) {
	o := orm.NewOrm()

	m := &ChatError{Id: id, Issuccess: issucc}

	if issucc == 0 {
		temErr := &ChatError{Id: id}
		err = o.Read(temErr)
		if err != nil {
			return
		}
		m.Syncnum = m.Syncnum + 1
	}
	_, err = o.Update(m, "Issuccess", "Syncnum")

	return
}
